import { defineStore } from "pinia";
import { RouteMeta, RouteRecordRaw } from "vue-router";
import { asyncRoutes, constantRoutes } from "@/router/index";

/** 路由类型 */
type StateType = {
  /** 所有路由 */
  routes: Array<RouteRecordRaw>;
  /** 权限路由 */
  addRoutes: Array<RouteRecordRaw>;
};

/**
 * 使用 meta.role 来确定当前用户是否具有权限
 * @param roles
 * @param route
 */
function hasPermission(roles: Array<string>, route: RouteRecordRaw) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) =>
      ((route.meta as RouteMeta).roles as Array<string>).includes(role)
    );
  } else {
    return false;
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(
  routes: Array<RouteRecordRaw>,
  roles: Array<string>
) {
  const res: Array<RouteRecordRaw> = [];

  routes.forEach((route) => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}

export const usePermissionStore = defineStore({
  id: "permission", // id必填，且需要唯一
  state: (): StateType => {
    return {
      routes: [],
      addRoutes: [],
    };
  },
  actions: {
    /** 添加动态路由 */
    generateRoutes(roles: Array<string>): Promise<Array<RouteRecordRaw>> {
      return new Promise((resolve) => {
        // 在这判断是否有权限，哪些角色拥有哪些权限
        let accessedRoutes: Array<RouteRecordRaw>;
        if (roles && roles.length && !roles.includes("admin")) {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
        } else {
          accessedRoutes = asyncRoutes || [];
        }
        this.addRoutes = accessedRoutes;
        this.routes = constantRoutes.concat(accessedRoutes);
        resolve(accessedRoutes);
      });
    },
    /** 清空路由 */
    clearRoutes() {
      this.addRoutes = [];
      this.routes = [];
    },
  },
});
